import path from 'path'

const getRoutesChildren = routes => {
  const result = []
  routes.forEach(item => {
    if (item.children && item.children.length > 0) {
      result.push(...item.children)
    }
  })
  return result
}

export const filterRouter = routes => {
  const routesChildren = getRoutesChildren(routes)
  return routes.filter(item => {
    return !routesChildren.find(routeChildren => routeChildren.path === item.path)
  })
}

const isNull = (data) => {
  if (!data) return true
  if (JSON.stringify(data) === '[]') return true
  if (JSON.stringify(data) === '{}') return true
  return false
}

export const generateMenus = (routes, basePath = '') => {
  const result = []
  routes.forEach(item => {
    if (isNull(item.children) && isNull(item.meta)) return false
    if (!isNull(item.children) && isNull(item.meta)) {
      result.push(...generateMenus(item.children))
    }
    const routePath = path.resolve(basePath, item.path)
    let route = result.find(item => item.path === routePath)
    if (!route) {
      route = {
        ...item,
        path: routePath,
        children: []
      }
      if (route.meta.icon && route.meta.title) {
        result.push(route)
      }
    }
    if (!isNull(item.children)) {
      route.children.push(...generateMenus(item.children, item.path))
    }
  })
  return result
}
